<template>
    <van-nav-bar
    title="客服聊天"
    left-text="返回"
    left-arrow
    fixed
    safe-area-inset-top
    @click-left="goBack"
    class="nav-bar"
  ></van-nav-bar>
  <div style=" overflow: auto;height: 60%;width: 100%;position: absolute;top: 50px;">
        <van-cell 
            v-for="i in data" 
            :title="i.type"
            :value="new Date().toLocaleTimeString()"
        >
            <template #label>
                <textarea style="width: 100%;white-space: pre-wrap; overflow-wrap: break-word; padding: 5px;border: none;">{{i.msg}}</textarea>
            </template>
        </van-cell>
  </div>
  <div style="position: absolute;top:70%"> <textarea v-model="msg" placeholder="请输入消息" 
                                            style=" width: 100%;
                                                    height: 150px;
                                                    resize: none; /* 禁止用户调整大小 */
                                                    white-space: pre-wrap; /* 自动换行 */
                                                    overflow-wrap: break-word; /* 单词过长时换行 */
                                                    padding: 5px; /* 可选：调整内边距 */
                                                    "
                                            ></textarea>
<button @click="sendmes">发送消息</button><button @click="stopws">结束会话</button></div>
  </template>
  
<script lang="ts" setup>
  import {ref,onMounted}  from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  const route = useRoute()
  const router = useRouter()
  
  
  const goBack = () => {
  if (window.history.state.back) {
    router.go(-1);
  } else {
    router.push('/');
  }
};
  const stopws = () => {
    socket.value.close()
  }
  const userid=ref(localStorage.getItem('userid'))
  //搜索用的
  const socket = ref(null)
  const data = ref([])
  const msg = ref('')
  const sendmes = () => {
    if(socket.value==null){
      initwesockt()
    }
  if (!msg.value.trim()) {
    alert('消息不能为空')
    return
  }
  
  try {
    const payload = JSON.stringify({ 
      type: '用户', 
      text: msg.value 
    })
    socket.value.send(payload)
    msg.value = '' // 清空输入框
  } catch (e) {
    console.error('发送失败:', e)
  }
}
  
  
  
  
  const initwesockt=()=>{

      socket.value = new WebSocket("ws://127.0.0.1:8000/room/"+(Math.floor(Math.random() * 9000 + 1000) | 0)+userid.value+"/");

      socket.value.onopen = (event)=>{
        data.value.push({msg:'连接成功,请等待客服进入',type:'',time:new Date().toLocaleTimeString()})
          console.log("连接成功")
      }

      socket.value.onmessage = (event)=>{
          try {
              const parsedData = {
                msg: JSON.parse(event.data).data,
                type: JSON.parse(event.data).action,
                timestamp: new Date().toISOString()
                };
                data.value = [...data.value, parsedData];
                console.log(data.value)
                console.log("收到消息:", parsedData);
          } catch(e) {
              console.error('消息解析失败:', e);
          }
      }

      socket.value.onclose = (event)=>{
          console.log("连接关闭")
      }

      socket.value.onerror = (error)=>{
          console.error('WebSocket错误:', error)
      }
  
      // // 当断开连接时，触发该函数
      // this.socket.onclose =function (event){
      // let tag = document.createElement("div");
      // tag.innerText = "[连接断开]";
      // document.getElementById("message").appendChild(tag);
      // }
  
  
  }
  
  onMounted(()=>{
    //   initwesockt()
  })
  </script>
<style scoped>
* {
   box-sizing: border-box;
}
</style>